# planting_records/views.py
from django.shortcuts import redirect # Add redirect import
from django.urls import reverse_lazy, reverse
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib import messages
from django.utils.translation import gettext as _
from django.core.exceptions import PermissionDenied # Import PermissionDenied

from .models import PlantingRecord
from .forms import PlantingRecordForm
from field_management.models import Field # Need Field model

# Mixin to check ownership for planting records
class PlantingRecordOwnerRequiredMixin(UserPassesTestMixin):
    def test_func(self):
        record = self.get_object()
        # User must own the record itself
        return self.request.user == record.owner

    def handle_no_permission(self):
        messages.error(self.request, _("您无权访问此记录。"))
        # Redirect to the general list or maybe the field detail?
        # Let's redirect to the record list for simplicity.
        return redirect(reverse_lazy('planting_records:record_list'))


class PlantingRecordListView(LoginRequiredMixin, ListView):
    model = PlantingRecord
    template_name = 'planting_records/record_list.html'
    context_object_name = 'records'
    paginate_by = 15

    def get_queryset(self):
        queryset = PlantingRecord.objects.filter(owner=self.request.user).select_related('field') # Optimize query
        self.field_filter = None # Initialize filter attribute

        # Allow filtering by field if field_id is passed in URL or GET param
        field_id = self.kwargs.get('field_id') or self.request.GET.get('field')
        if field_id:
            try:
                # Ensure the user owns the field they are filtering by
                self.field_filter = Field.objects.get(id=field_id, owner=self.request.user)
                queryset = queryset.filter(field=self.field_filter)
            except Field.DoesNotExist:
                 messages.warning(self.request, _("无法按指定的田块筛选，因为它不存在或不属于您。"))
                 # Optionally redirect or just show all records
                 # return PlantingRecord.objects.none() # Or just proceed without filter

        return queryset.order_by('-planting_date')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['selected_field'] = getattr(self, 'field_filter', None) # Pass the filtered field object to template
        context['page_title'] = _('种植记录')
        if context['selected_field']:
             context['page_title'] += f" ({_('田块')}: {context['selected_field'].name})"
        return context


class PlantingRecordDetailView(LoginRequiredMixin, PlantingRecordOwnerRequiredMixin, DetailView):
    model = PlantingRecord
    template_name = 'planting_records/record_detail.html'
    context_object_name = 'record'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['page_title'] = _("种植记录详情")
        return context

class PlantingRecordCreateView(LoginRequiredMixin, CreateView):
    model = PlantingRecord
    form_class = PlantingRecordForm
    template_name = 'planting_records/record_form.html'
    # success_url = reverse_lazy('planting_records:record_list') # Or use get_absolute_url

    def get_initial(self):
        # Pre-fill field if 'field_id' is in URL kwargs
        initial = super().get_initial()
        field_id = self.kwargs.get('field_id')
        if field_id:
            try:
                # Verify user owns the field before pre-filling
                field = Field.objects.get(id=field_id, owner=self.request.user)
                initial['field'] = field
            except Field.DoesNotExist:
                # Raise permission denied or handle gracefully
                # messages.error(self.request, _("无法为指定的田块添加记录。"))
                # Or let the form handle the invalid choice later
                pass
        return initial

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user # Pass user to the form __init__
        return kwargs

    def form_valid(self, form):
        form.instance.owner = self.request.user
        # If field was pre-filled via URL but doesn't belong to user, this check prevents saving
        # The form's field queryset should already handle this if user is passed correctly
        if form.cleaned_data['field'].owner != self.request.user:
             messages.error(self.request, _("您不能为不属于您的田块添加记录。"))
             return self.form_invalid(form) # Treat as invalid form

        messages.success(self.request, _("种植记录已成功添加。"))
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['view_title'] = _('添加种植记录')
        # Add selected field info if adding via specific field URL
        field_id = self.kwargs.get('field_id')
        if field_id:
             try:
                 context['selected_field'] = Field.objects.get(id=field_id, owner=self.request.user)
             except Field.DoesNotExist:
                 pass # Handle error or ignore
        return context

    # Redirect to the newly created record's detail page upon success
    def get_success_url(self):
         return self.object.get_absolute_url()


class PlantingRecordUpdateView(LoginRequiredMixin, PlantingRecordOwnerRequiredMixin, UpdateView):
    model = PlantingRecord
    form_class = PlantingRecordForm
    template_name = 'planting_records/record_form.html'

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user # Pass user to form for field queryset filtering
        return kwargs

    def form_valid(self, form):
        # Ensure the selected field still belongs to the user (in case it changed)
        if form.cleaned_data['field'].owner != self.request.user:
             messages.error(self.request, _("您不能将记录关联到不属于您的田块。"))
             return self.form_invalid(form)

        messages.success(self.request, _("种植记录已成功更新。"))
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['view_title'] = _('编辑种植记录')
        return context

    # Redirect to the record's detail page upon success
    def get_success_url(self):
         return self.object.get_absolute_url()


class PlantingRecordDeleteView(LoginRequiredMixin, PlantingRecordOwnerRequiredMixin, DeleteView):
    model = PlantingRecord
    template_name = 'planting_records/record_confirm_delete.html'
    success_url = reverse_lazy('planting_records:record_list') # Redirect to list after delete

    def form_valid(self, form):
        messages.success(self.request, _("种植记录已成功删除。"))
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['view_title'] = _('删除确认')
        return context